<?php

namespace app\api\controller;


use app\api\model\ClusterUser;
use app\api\model\GradeCharm;
use app\api\model\GradeCluster;
use app\api\model\GradeTycoon;
use think\Db;
use think\Log;
use think\Request;
use app\api\model\Cluster;
use app\api\model\ConfigSystem as Config;
use app\api\model\User;
use app\api\model\Privatechat;
use app\api\model\Task;

class Family extends Common
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        exit(json_encode(['code'=>200, 'data'=>[]]));
    }
    public function create(Request $request = null)
    {
        $config = Config::index('', 'create');

        $gradeTycoon = GradeTycoon::where(['min' => ['elt', $this->member['tycoon']]])->order('grade desc')->find();
        $gradeCharm = GradeCharm::where(['min' => ['elt', $this->member['charm_value']]])->order('grade desc')->find();

        if ($gradeTycoon['grade'] < $config['create'] && $gradeCharm['grade'] < $config['create']) {
            return $this->miss('土豪等级、魅力等级其中一项达到等级'.$config['create'].'才可创建');
        }

        $result = Cluster::get(['types' => 1, 'user_id' => $this->params['user_id']]);

        if ($result) {
            return $this->miss('已创建过家族');
        }

        $this->params['create_time'] = time();

        $cluster = Cluster::create($this->params);
        ClusterUser::create([
            'cluster_id' => $cluster->id,
            'user_id' => $this->params['user_id'],
            'is_founder' => 1,
            'identity' => 1,
            'status' => 1,
            'identity_status' => 1,
            'create_time' => time(),
            'update_time' => time(),
        ]);

        return $this->return['common.success.create'];
    }

    public function lists(Request $request = null)
    {
        $where = 'types =1 and status = 1';
        $order = 'id desc';

        if ($request->param('same_city') && $this->member['city']) {
            $where .= ' and city LIKE "%' . $this->member['city'] . '%"';
        }

        if ($request->param('search')) {
            $where .= ' and name LIKE "%' . $this->params['search'] . '%"';
        }

        if ($request->param('nearby')) {
            $where .= ' having (distance <= 50000)';
        }

        if ($request->param('order')) {
            $active = $this->params['order'] == 'sum' ? '' : '_' . $this->params['order'];
            $order = 'active' . $active . ' desc';
        }

        $distance_sql = distanceBase($this->member['latitude'], $this->member['longitude']);

        $page = $request->param('page') ?: 1;
        $pagesize = $request->param('pagesize') ?: 10;
        $page = ($page - 1) * $pagesize;

        $field = 'id, name, count, logo, description, active, active_day';

        $sql = "select $field, $distance_sql from cluster where $where order by $order limit $page, $pagesize";

        $data = Db::query($sql);

        $clusters = ClusterUser::where(['user_id' => $this->member['id'], 'status' => 1])->column('cluster_id');

        foreach ($data as $key => $item) {
            if (in_array($item['id'], $clusters)) {
                $data[$key]['is_join'] = 1;
            } else {
                $data[$key]['is_join'] = 0;
            }
        }

        return $this->pass($data);
    }

    public function info()
    {
        $cluster = Cluster::get(['id' => $this->params['id'], 'status' => 1]);

        if (!$cluster) return $this->return['common.error.notExist'];

        $ranking_week = Db::name('cluster')->where(['status' => 1])->order('active_week desc')->column('id');
        $cluster['rank_week'] = array_search($this->params['id'], $ranking_week) + 1;

        $ranking = Db::name('cluster')->where(['status' => 1])->order('active desc')->column('id');
        $cluster['rank'] = array_search($this->params['id'], $ranking) + 1;

        //$nextGrade = GradeCluster::get($cluster['grade'] + 1);

        $nextGrade = GradeCluster::where(['min' => ['gt', $cluster['active']]])->order('grade asc')->find();

        $cluster['nextGrade'] = $nextGrade['min'] - $cluster['active'];

        $founder = User::get($cluster['user_id']);

        if ($founder) {
            $cluster['founder_name'] = $founder['name'];
            $cluster['founder_avatar'] = $founder['head_100'];
            $cluster['founder_sex'] = $founder['sex'];
            $cluster['founder_age'] = $founder['age'];
            $cluster['founder_is_identity_authentication'] = $founder['is_identity_authentication'];
        } else {
            $cluster['founder_name'] = '匿名用户';
            $cluster['founder_avatar'] = '/public/style/api/img/male/' . mt_rand(1,20) . '.jpg';
            $cluster['founder_sex'] = '男';
            $cluster['founder_age'] = '20';
            $cluster['founder_is_identity_authentication'] = 0;
        }

        $clusterUser = ClusterUser::get(['cluster_id' => $cluster['id'], 'user_id' => $this->params['user_id']]);

        if ($clusterUser) {
            $cluster['identity'] = $clusterUser['identity'];
            $cluster['ban_chat'] = $clusterUser['ban_chat'];

            $signIn = Db::name('cluster_sign_in')
                ->where(['cluster_id' => $cluster['id'], 'user_id' => $this->params['user_id']])
                ->whereTime('create_time', 'd')->find();

            $cluster['sign_in'] = $signIn ? 1 : 0;
        }

        $cluster['status'] = $clusterUser ? $clusterUser['status'] : -2;

        $cluster['users'] = Db::name('cluster_user t1')
            ->join('user t2', 't2.id = t1.user_id')
            ->field('t2.id, t2.name, t2.head_100')
            ->where(['t1.cluster_id' => $cluster['id'], 'status' => 1])
            ->order('identity = 0, identity asc')
            ->page(1,5)->select();

        return $this->pass($cluster);
    }

    public function apply(Request $request = null)
    {
        $cluster = Cluster::get(['types' => 1, 'id' => $this->params['id']]);

        if (!$cluster) {
            return $this->return['common.error.notExist'];
        }

        //$result = ClusterUser::get(['user_id' => $this->params['user_id'], 'status' => ['in', [0,1]]]);

        $result = Db::name('cluster_user t1')->join('cluster t2', 't2.id = t1.cluster_id')->where([
            't2.types' => 1, 't1.user_id' => $this->params['user_id'], 't1.status' => ['in', [0,1]]])->find();

        if ($result) return $this->miss('已有加入的家族或申请加入的家族');

        $data = ClusterUser::get(['cluster_id' => $this->params['id'], 'user_id' => $this->params['user_id']]);

        if ($data) {

            if ($data['status'] == 1) {
                return $this->miss('已是家族成员');
            } else if (!$data['status'] && (strtotime($data['create_time']) + 86400 * 3) > time()) {

                return $this->miss('待审核');
            }

            ClusterUser::update([
                'id' => $data['id'],
                'reason' => $request->param('reason'),
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ]);

            $apply_id = $data['id'];
        } else {
            $apply = ClusterUser::create([
                'cluster_id' => $this->params['id'],
                'user_id' => $this->params['user_id'],
                'reason' => $request->param('reason'),
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ]);

            $apply_id = $apply->id;
        }

        $content = '用户' . $this->member['name'] . '(' . $this->member['id'] . ')申请加入家族，申请理由：' . $request->param('reason');

        $data = json_encode([
            'cluster_id' => $this->params['id'],
            'apply_id' => $apply_id,
            'apply_user' => $this->member['id'],
            'apply_name' => $this->member['name'],
            'apply_reason' => $request->param('reason'),
        ],JSON_UNESCAPED_UNICODE);

        $ids = Db::name('cluster_user')->where([
            'cluster_id' => $this->params['id'],
            'identity' => ['in', [1,2,3]],
            'identity_status' => 1
        ])->column('user_id');

        if ($ids) {
            $chat_ids = [];
            foreach ($ids as $item) {
                $chat_id = Privatechat::notice($item, $content, $data, 1);
    
                $chat_ids[] = $chat_id;
            }
    
            ClusterUser::update(['id' => $apply_id, 'data' => json_encode(['chat_id' => implode(',', $chat_ids)])]);
        }
        
        return $this->pass('申请已提交');
    }

    public function quit(Request $request = null)
    {
        $cluster = Cluster::get(['types' => 1, 'id' => $this->params['id']]);

        if (!$cluster) {
            return $this->return['common.error.notExist'];
        }

        $data = ClusterUser::get([
            'cluster_id' => $this->params['id'],
            'user_id' => $this->member['id'],
            'status' => 1
        ]);

        if (!$data) return $this->return['family.error.notJoined'];

        if ($data['is_founder']) {
            return $this->return['family.error.unableToExit'];
        }

        ClusterUser::destroy($data['id']);

        Cluster::where(['id' => $cluster['id']])->setDec('count');

        return $this->return['family.success.exitSuccessfully'];
    }

    public function check()
    {
        $data = ClusterUser::get($this->params['id']);

        if (!$data) return $this->return['common.error.notExist'];

        if (!in_array($this->params['status'], [-1,1])) {
            return $this->return['common.error.default'];
        }

        if ($data['status'] != 0) {
            return $this->return['common.error.hadHandle'];
        }

        $cluster = Cluster::get($data['cluster_id']);

        if ($cluster['user_id'] != $this->params['user_id']) {
            $clusterUser = ClusterUser::get($this->member['id']);

            if (!$clusterUser || !in_array($clusterUser['identity'], [2,3]) || $clusterUser['identity_status'] != 1) {
                return $this->return['common.error.noPermission'];
            }
        }

        $chat_ids = json_decode($data['data'], true)['chat_id'];
        $chat_ids = explode(',', $chat_ids);

        /*$chat = Privatechat::get($chat_id);

        if ($chat['state']) {
            return $this->return['common.error.hadHandle'];
        }*/

        ClusterUser::update([
            'id' => $data['id'],
            'status' => $this->params['status'],
            'update_time' => time(),
        ]);

        if ($this->params['status'] == 1) {
            Cluster::where(['id' => $data['cluster_id']])->setInc('count');

            $content = '你申请加入家族[' . $cluster['name'] . ']已通过';

            // 任务
            Task::finish('join_family', $data['user_id']);
        } else {
            $content = '很遗憾，你申请加入家族[' . $cluster['name'] . ']未通过';
        }

        Privatechat::notice($data['user_id'], $content);

        if ($chat_ids) {
            Privatechat::update(['id' => ['in', $chat_ids], 'state' => 1]);
        }
        
        return $this->pass('已处理');
    }

    public function myFamily()
    {
        $data = ClusterUser::get(['user_id' => $this->params['user_id'], 'status' => 1]);

        if ($data) {
            $cluster = Cluster::where(['id' => $data['cluster_id'], 'types' => 1])
                ->field('id, name, count,logo,description,grade,active')->find();

            if ($cluster) {
                $cluster['users'] = Db::name('cluster_user t1')
                    ->join('user t2', 't2.id = t1.user_id')
                    ->field('t2.id, t2.name, t2.head_100')
                    ->where(['t1.cluster_id' => $cluster['id']])
                    ->page(1,5)->select();
            } else {
                $cluster = (object)[];
            }
        } else {
            $cluster = (object)[];
        }

        return $this->pass($cluster);
    }

    // 解散家族
    public function dissolve()
    {
        $cluster = Cluster::get($this->params['id']);

        if ($cluster['user_id'] != $this->params['user_id']) {
            return $this->return['common.error.noPermission'];
        }

        $ids = Db::name('cluster_user')->where([
            'cluster_id' => $cluster['id'],
            'identity' => ['neq', 1],
            'identity_status' => 1
        ])->column('user_id');

        $content = '家族[' . $cluster['name'] . ']已被族长解散';

        foreach ($ids as $item) {
            Privatechat::notice($item, $content, '', 1);
        }

        $content = '你已解散家族[' . $cluster['name'] . ']';

        Privatechat::notice($this->params['user_id'], $content);

        ClusterUser::destroy(['cluster_id' => $cluster['id']]);

        Cluster::destroy($cluster['id']);

        return $this->return['family.success.dissolve'];
    }

    // 家族身份申请
    public function applyIdentity(Request $request = null)
    {
        $cluster = Cluster::get(['types' => 1, 'id' => $this->params['id']]);

        if (!$cluster) {
            return $this->return['common.error.notExist'];
        }

        $data = ClusterUser::get(['cluster_id' => $this->params['id'], 'user_id' => $this->member['id']]);

        if ($data) {
            if ($data['is_founder']) {
                return $this->return['family.error.noChange'];
            }

            if (!$data['identity_status']) {
                return $this->miss('待审核');
            }

            if ($data['identity'] == $this->params['identity']) {
                return $this->return['family.error.noChange'];
            }

            ClusterUser::update([
                'id' => $data['id'],
                'identity_apply' => $this->params['identity'],
                'identity_status' => 0,
                'identity_reason' => $request->param('reason'),
            ]);

            $apply_id = $data['id'];
        } else {
            return $this->return['common.error.notExist'];
        }

        $identity_msg = ['', '', '副族长', '长老'];

        $content = '用户' . $this->member['name'] . '(' . $this->member['id'] . ')申请家族'.$identity_msg[$this->params['identity']].'身份，申请理由：' . $request->param('reason');

        $data = json_encode([
            'cluster_id' => $this->params['id'],
            'apply_id' => $apply_id,
            'apply_user' => $this->member['id'],
            'apply_name' => $this->member['name'],
            'apply_reason' => $request->param('reason'),
            'apply_identity' => '申请家族' . $identity_msg[$this->params['identity']].'身份',
        ],JSON_UNESCAPED_UNICODE);

        $chat_id = Privatechat::notice($cluster['user_id'], $content, $data, 2);

        ClusterUser::update(['id' => $apply_id, 'data' => json_encode(['chat_id' => $chat_id])]);

        return $this->pass('申请已提交');
    }

    // 处理家族身份申请
    public function checkIdentity()
    {
        $data = ClusterUser::get($this->params['id']);

        if (!$data) return $this->return['common.error.notExist'];

        if (!in_array($this->params['status'], [-1,1])) {
            return $this->return['common.error.default'];
        }

        if ($data['identity_status'] != 0) {
            return $this->return['common.error.hadHandle'];
        }

        $cluster = Cluster::get($data['cluster_id']);

        if (!$cluster) return $this->return['common.error.notExist'];

        if ($cluster['user_id'] != $this->params['user_id']) {
            return $this->return['common.error.noPermission'];
        }

        $chat_id = json_decode($data['data'], true)['chat_id'];

        $chat = Privatechat::get($chat_id);

        if ($chat['state']) {
            return $this->return['common.error.hadHandle'];
        }

        $update = [
            'id' => $data['id'],
            'identity_status' => $this->params['status'],
        ];

        if ($this->params['status'] == 1) {
            $update['identity'] = $data['identity_apply'];
        }

        ClusterUser::update($update);

        $identity_msg = ['', '', '副族长', '长老'];

        if ($this->params['status'] == 1) {
            $content = '你申请家族[' . $cluster['name'] . ']'.$identity_msg[$data['identity']].'身份已通过';
        } else {
            $content = '很遗憾，你申请家族[' . $cluster['name'] . ']'.$identity_msg[$data['identity']].'身份未通过';
        }

        Privatechat::notice($data['user_id'], $content);

        Privatechat::update(['id' => $chat_id, 'state' => 1]);

        return $this->pass('已处理');
    }

    // 禁言
    public function changeChat()
    {
        $cluster_user = ClusterUser::get(['cluster_id' => $this->params['cluster_id'], 'user_id' => $this->params['id']]);

        $user = ClusterUser::get(['cluster_id' => $this->params['cluster_id'], 'user_id' => $this->member['id']]);

        if ($user['identity_status'] != 1 || !$user['identity'] || ($cluster_user['identity'] && $user['identity'] >= $cluster_user['identity'])) {
            return $this->return['common.error.noPermission'];
        }

        if ($cluster_user['ban_chat']) {
            $ban_chat = 0;
            $msg = '发言禁止已解除';
        } else {
            $ban_chat = 1;
            $msg = '已禁止发言';
        }

        ClusterUser::update(['id' => $cluster_user['id'], 'ban_chat' => $ban_chat]);

        return $this->pass($msg);
    }

    // 踢人
    public function remove()
    {
        if ($this->params['id'] == $this->member['id']) {
            return $this->return['common.error.noPermission'];
        }

        $cluster_user = ClusterUser::get(['cluster_id' => $this->params['cluster_id'], 'user_id' => $this->params['id']]);

        $user = ClusterUser::get(['cluster_id' => $this->params['cluster_id'], 'user_id' => $this->member['id']]);

        if ($user['identity_status'] != 1 || !$user['identity'] || ($cluster_user['identity'] && $user['identity'] >= $cluster_user['identity'])) {
            return $this->return['common.error.noPermission'];
        }

        ClusterUser::destroy(['id' => $cluster_user['id']]);

        Cluster::where(['id' => $cluster_user['cluster_id']])->setDec('count');

        return $this->pass('已移出');
    }

    // 家族签到
    public function signIn()
    {
        $cluster = Cluster::get(['id' => $this->params['id'], 'status' => 1]);

        if ($cluster['types'] != 1) return $this->return['family.error.notExist'];

        $clusterUser = Db::name('cluster_user')->where([
            'cluster_id' => $this->params['id'],
            'user_id' => $this->member['id'],
            'status' => 1
        ]);

        if (!$clusterUser) return $this->return['family.error.notJoined'];

        $signIn = Db::name('cluster_sign_in')
            ->where(['cluster_id' => $this->params['id'], 'user_id' => $this->member['id']])
            ->order('id desc')->find();

        $today = strtotime(date('Ymd'));

        $days = 1;
        if ($signIn) {
            if ($signIn['create_time'] >= $today) return $this->return['sign.error.exist'];

            if ($signIn['create_time'] < ($today + 86400)) {
                $days = $signIn['days'] + 1;
            }
        }

        Db::name('cluster_sign_in')->insert([
            'cluster_id' => $this->params['id'],
            'user_id' => $this->member['id'],
            'days' => $days,
            'create_time' => time(),
        ]);

        // 群威望
        Cluster::active($this->params['id'], 1);

        return $this->return['sign.success.default'];
    }

    // 家族邀请
    public function invite()
    {
        $cluster = Cluster::get(['id' => $this->params['id'], 'status' => 1]);

        if ($cluster['types'] != 1) return $this->return['family.error.notExist'];

        $clusterUser = ClusterUser::get(['cluster_id' => $this->params['id'], 'user_id' => $this->params['to_user']]);

        if ($clusterUser) {
            switch ($clusterUser['status']) {
                case 0:
                    return $this->return['family.error.checking'];
                case 1:
                    return $this->return['family.error.hadJoined'];
            }
        }

        $datas = [
            'userid' => $this->member['id'],
            'touserid' => $this->params['to_user'],
            'content' => '我邀请你加入 ' . $cluster['name'] . '，一群帅哥美女陪你嗨，快来申请吧。点击申请加入',
            'location' => 1,
            'greet' => 1,
            'data' => json_encode([
                'cluster_id' => $this->params['id'],
                'cluster_name' => $cluster['name'],
            ], JSON_UNESCAPED_UNICODE),
            'timing' => 1
        ];

        $request = request();
        $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';
        curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));

        return $this->return['family.success.invite'];
    }
}
